<template>
  <div class="devices-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>设备管理</h2>
        <p>管理和监控ONVIF设备</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="addDevice"> 添加设备 </el-button>
        <el-button type="success" :icon="Search" @click="discoverDevices"> 发现设备 </el-button>
        <el-button :icon="Refresh" @click="refreshDevices"> 刷新 </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-row">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索设备名称、IP地址或制造商"
            :prefix-icon="Search"
            clearable
            style="width: 300px"
            @input="handleSearch"
          />
          <el-select
            v-model="statusFilter"
            placeholder="设备状态"
            clearable
            style="width: 120px"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="连接中" value="connecting" />
            <el-option label="错误" value="error" />
          </el-select>
          <el-select
            v-model="manufacturerFilter"
            placeholder="制造商"
            clearable
            style="width: 120px"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="manufacturer in manufacturers"
              :key="manufacturer"
              :label="manufacturer"
              :value="manufacturer"
            />
          </el-select>
          <el-select
            v-model="enabledFilter"
            placeholder="启用状态"
            clearable
            style="width: 120px"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="已启用" value="true" />
            <el-option label="已禁用" value="false" />
          </el-select>
        </div>
        <div class="filter-right">
          <el-button-group>
            <el-button
              :type="viewMode === 'table' ? 'primary' : ''"
              :icon="List"
              @click="viewMode = 'table'"
            >
              列表
            </el-button>
            <el-button
              :type="viewMode === 'grid' ? 'primary' : ''"
              :icon="Grid"
              @click="viewMode = 'grid'"
            >
              网格
            </el-button>
          </el-button-group>
          <el-dropdown @command="handleBatchAction">
            <el-button :disabled="selectedDevices.length === 0">
              批量操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="enable">启用设备</el-dropdown-item>
                <el-dropdown-item command="disable">禁用设备</el-dropdown-item>
                <el-dropdown-item command="refresh">刷新状态</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除设备</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-card>

    <!-- 设备统计 -->
    <div class="stats-row">
      <el-card class="stat-item" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon online">
            <el-icon><VideoCamera></VideoCamera></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ onlineDeviceCount }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-item" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Monitor></Monitor></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalDeviceCount }}</div>
            <div class="stat-label">总设备数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-item" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon enabled">
            <el-icon><CircleCheck></CircleCheck></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ enabledDeviceCount }}</div>
            <div class="stat-label">已启用</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-item" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon disabled">
            <el-icon><CircleClose></CircleClose></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ disabledDeviceCount }}</div>
            <div class="stat-label">已禁用</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 设备列表 -->
    <el-card class="device-list-card" shadow="never">
      <!-- 表格视图 -->
      <el-table
        v-if="viewMode === 'table'"
        v-loading="loading"
        :data="filteredDevices"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="设备名称" sortable min-width="150">
          <template #default="{ row }">
            <div class="device-name-cell">
              <el-avatar :size="32" class="device-avatar">
                <el-icon><VideoCamera></VideoCamera></el-icon>
              </el-avatar>
              <div class="device-info">
                <div class="name">{{ row.name }}</div>
                <div class="model">{{ row.model }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备ID" width="160" />
        <el-table-column prop="ipAddress" label="IP地址" width="140" />
        <el-table-column prop="username" label="用户名" width="120">
          <template #default="{ row }">
            {{ row.username || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" width="140">
          <template #default="{ row }">
            <div class="password-cell" v-if="row.password">
              <span v-if="!passwordVisibility[row.id]" class="password-masked">
                {{ '●'.repeat(Math.min(row.password.length, 8)) }}
              </span>
              <span v-else class="password-visible">
                {{ row.password }}
              </span>
              <el-button
                text
                size="small"
                :icon="passwordVisibility[row.id] ? Hide : View"
                @click="togglePasswordVisibility(row.id)"
                class="password-toggle"
              />
            </div>
            <span v-else>{{ row.password === null || row.password === undefined ? 'Unknown' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="manufacturer" label="制造商" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getDeviceStatusType(row.status)" size="small">
              {{ getDeviceStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用" width="80">
          <template #default="{ row }">
            <el-switch v-model="row.enabled" @change="toggleDevice(row)" />
          </template>
        </el-table-column>
        <el-table-column prop="channelCount" label="通道数" width="80" />
        <el-table-column prop="lastSeen" label="最后在线" width="160">
          <template #default="{ row }">
            {{ formatRelativeTime(row.lastSeen) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group size="small">
              <el-button type="primary" @click="viewDevice(row)"> 查看 </el-button>
              <el-button @click="editDevice(row)"> 编辑 </el-button>
              <el-button @click="viewChannels(row)"> 通道 </el-button>
              <el-button @click="testConnection(row)"> 测试 </el-button>
              <el-button type="danger" @click="deleteDevice(row)"> 删除 </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 网格视图 -->
      <div v-else class="device-grid">
        <div
          v-for="device in filteredDevices"
          :key="device.id"
          class="device-card"
          :class="{ selected: selectedDevices.includes(device.id) }"
          @click="selectDevice(device)"
        >
          <div class="card-header">
            <el-checkbox
              :model-value="selectedDevices.includes(device.id)"
              @change="toggleSelection(device)"
              @click.stop
            />
            <el-dropdown @command="command => handleDeviceAction(command, device)">
              <el-button text :icon="MoreFilled" @click.stop />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="view">查看详情</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑设备</el-dropdown-item>
                  <el-dropdown-item command="test">测试连接</el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新状态</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除设备</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="card-body">
            <div class="device-avatar-large">
              <el-avatar :size="60">
                <el-icon><VideoCamera></VideoCamera></el-icon>
              </el-avatar>
              <div class="device-status" :class="device.status"></div>
            </div>
            <div class="device-details">
              <h3 class="device-name">{{ device.name }}</h3>
              <p class="device-model">{{ device.model }}</p>
              <p class="device-id">ID: {{ device.deviceId }}</p>
              <p class="device-ip">{{ device.ipAddress }}</p>
              <p class="device-manufacturer">{{ device.manufacturer }}</p>
            </div>
          </div>
          <div class="card-footer">
            <div class="device-stats">
              <span class="stat-item">
                <el-icon><Connection></Connection></el-icon>
                {{ device.channelCount }} 通道
              </span>
              <span class="stat-item">
                <el-icon><Clock></Clock></el-icon>
                {{ formatRelativeTime(device.lastSeen) }}
              </span>
            </div>
            <div class="device-actions">
              <el-switch v-model="device.enabled" @change="toggleDevice(device)" @click.stop />
              <el-tag :type="getDeviceStatusType(device.status)" size="small">
                {{ getDeviceStatusLabel(device.status) }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredDevices.length === 0" class="empty-state">
          <el-empty description="暂无设备" :image-size="120">
            <el-button type="primary" @click="addDevice"> 添加设备 </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="filteredDevices.length > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备详情抽屉 -->
    <el-drawer v-model="deviceDetailVisible" :title="currentDevice?.name || '设备详情'" size="50%">
      <DeviceDetail
        v-if="currentDevice"
        :device="currentDevice"
        @refresh="refreshDevices"
        @close="deviceDetailVisible = false"
        @edit="handleDeviceDetailEdit"
      />
    </el-drawer>

    <!-- 设备通道列表抽屉 -->
    <el-drawer v-model="channelListVisible" :title="`${currentDevice?.name || '设备'} - 通道列表`" size="60%">
      <ChannelList
        v-if="currentDevice"
        :device-id="currentDevice.deviceId"
        :device-name="currentDevice.name"
        @close="channelListVisible = false"
      />
    </el-drawer>

    <!-- 添加/编辑设备对话框 -->
    <DeviceForm
      v-model="deviceFormVisible"
      :device="editingDevice"
      :is-editing="isEditing"
      @submit="handleDeviceSubmit"
      @cancel="deviceFormVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDeviceStore } from '@/stores/device'
import { formatRelativeTime, debounce } from '@/utils/common'
import { DEVICE_STATUS_LABELS, DEVICE_STATUS_COLORS, MANUFACTURERS } from '@/utils/constants'
import {
  Plus,
  Search,
  Refresh,
  List,
  Grid,
  VideoCamera,
  Monitor,
  CircleCheck,
  CircleClose,
  Connection,
  Clock,
  MoreFilled,
  ArrowDown,
  View,
  Hide
} from '@element-plus/icons-vue'
import DeviceDetail from './components/DeviceDetail.vue'
import DeviceForm from './components/DeviceForm.vue'
import ChannelList from './components/ChannelList.vue'

const router = useRouter()
const deviceStore = useDeviceStore()

// 响应式数据
const loading = ref(false)
const viewMode = ref('table')
const searchKeyword = ref('')
const statusFilter = ref('')
const manufacturerFilter = ref('')
const enabledFilter = ref('')
const selectedDevices = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const sortField = ref('')
const sortOrder = ref('')

// 设备详情
const deviceDetailVisible = ref(false)
const currentDevice = ref(null)

// 设备表单
const deviceFormVisible = ref(false)
const isEditing = ref(false)
const editingDevice = ref(null)

// 通道列表
const channelListVisible = ref(false)

// 密码显示控制
const passwordVisibility = ref({})

// 统计数据
const statistics = ref({
  totalDevices: 0,
  onlineDevices: 0,
  offlineDevices: 0,
  enabledDevices: 0,
  disabledDevices: 0,
  totalChannels: 0
})

// 计算属性
const devices = computed(() => deviceStore.devices)
const totalCount = computed(() => deviceStore.totalCount)
const manufacturers = computed(() => MANUFACTURERS)

// 使用后端统计数据而不是前端计算
const onlineDeviceCount = computed(() => statistics.value.onlineDevices)
const totalDeviceCount = computed(() => statistics.value.totalDevices)
const enabledDeviceCount = computed(() => statistics.value.enabledDevices)
const disabledDeviceCount = computed(() => statistics.value.disabledDevices)

const filteredDevices = computed(() => {
  let result = devices.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(
      device =>
        device.name.toLowerCase().includes(keyword) ||
        device.ipAddress.toLowerCase().includes(keyword) ||
        device.manufacturer.toLowerCase().includes(keyword)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(device => device.status === statusFilter.value)
  }

  // 制造商过滤
  if (manufacturerFilter.value) {
    result = result.filter(device => device.manufacturer === manufacturerFilter.value)
  }

  // 启用状态过滤
  if (enabledFilter.value !== '') {
    const enabled = enabledFilter.value === 'true'
    result = result.filter(device => device.enabled === enabled)
  }

  // 排序
  if (sortField.value) {
    result.sort((a, b) => {
      const aVal = a[sortField.value]
      const bVal = b[sortField.value]
      const order = sortOrder.value === 'ascending' ? 1 : -1

      if (aVal < bVal) return -1 * order
      if (aVal > bVal) return 1 * order
      return 0
    })
  }

  return result
})

// 方法
const getDeviceStatusType = status => {
  return DEVICE_STATUS_COLORS[status] || 'info'
}

const getDeviceStatusLabel = status => {
  return DEVICE_STATUS_LABELS[status] || status
}

// 搜索处理
const handleSearch = debounce(() => {
  currentPage.value = 1
  loadDevices()
}, 300)

// 过滤处理
const handleFilter = () => {
  currentPage.value = 1
  loadDevices()
}

// 排序处理
const handleSortChange = ({ prop, order }) => {
  sortField.value = prop
  sortOrder.value = order
  loadDevices()
}

// 选择处理
const handleSelectionChange = selection => {
  selectedDevices.value = selection.map(device => device.id)
}

const selectDevice = device => {
  if (selectedDevices.value.includes(device.id)) {
    selectedDevices.value = selectedDevices.value.filter(id => id !== device.id)
  } else {
    selectedDevices.value.push(device.id)
  }
}

const toggleSelection = device => {
  selectDevice(device)
}

// 分页处理
const handleSizeChange = size => {
  pageSize.value = size
  currentPage.value = 1
  loadDevices()
}

const handleCurrentChange = page => {
  currentPage.value = page
  loadDevices()
}

// 批量操作
const handleBatchAction = async command => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请选择要操作的设备')
    return
  }

  try {
    switch (command) {
      case 'enable':
        await deviceStore.batchToggleDevices(selectedDevices.value, true)
        ElMessage.success('批量启用成功')
        break
      case 'disable':
        await deviceStore.batchToggleDevices(selectedDevices.value, false)
        ElMessage.success('批量禁用成功')
        break
      case 'refresh':
        await deviceStore.batchRefreshDevices(selectedDevices.value)
        ElMessage.success('批量刷新成功')
        break
      case 'delete':
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedDevices.value.length} 个设备吗？`,
          '确认删除',
          { type: 'warning' }
        )
        await deviceStore.batchDeleteDevices(selectedDevices.value)
        ElMessage.success('批量删除成功')
        selectedDevices.value = []
        break
    }
    await Promise.all([loadDevices(), loadStatistics()])
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + error.message)
    }
  }
}

// 设备操作
const handleDeviceAction = (command, device) => {
  switch (command) {
    case 'view':
      viewDevice(device)
      break
    case 'edit':
      editDevice(device)
      break
    case 'test':
      testConnection(device)
      break
    case 'refresh':
      refreshDevice(device)
      break
    case 'delete':
      deleteDevice(device)
      break
  }
}

// 查看设备
const viewDevice = device => {
  currentDevice.value = device
  deviceDetailVisible.value = true
}

// 处理设备详情编辑
const handleDeviceDetailEdit = device => {
  deviceDetailVisible.value = false
  editDevice(device)
}

// 添加设备
const addDevice = () => {
  isEditing.value = false
  editingDevice.value = null
  deviceFormVisible.value = true
}

// 编辑设备
const editDevice = device => {
  isEditing.value = true
  editingDevice.value = { ...device }
  deviceFormVisible.value = true
}

// 查看设备通道
const viewChannels = device => {
  currentDevice.value = device
  channelListVisible.value = true
}

// 删除设备
const deleteDevice = async device => {
  try {
    await ElMessageBox.confirm(`确定要删除设备 "${device.name}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await deviceStore.deleteDevice(device.id)
    await Promise.all([loadDevices(), loadStatistics()])
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 切换设备启用状态
const toggleDevice = async device => {
  try {
    await deviceStore.toggleDevice(device.id, device.enabled)
    ElMessage.success(device.enabled ? '设备已启用' : '设备已禁用')
  } catch (error) {
    device.enabled = !device.enabled // 回滚状态
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 切换密码显示状态
const togglePasswordVisibility = (deviceId) => {
  passwordVisibility.value[deviceId] = !passwordVisibility.value[deviceId]
}

// 获取密码显示文本
const getPasswordDisplay = (device) => {
  if (!device.password) return '-'
  return passwordVisibility.value[device.id] ? device.password : '••••••••'
}

// 测试连接
const testConnection = async device => {
  try {
    loading.value = true
    const result = await deviceStore.testDeviceConnection(device.id)
    if (result.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败: ' + result.message)
    }
  } catch (error) {
    ElMessage.error('测试失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 刷新单个设备
const refreshDevice = async device => {
  try {
    await deviceStore.refreshDevice(device.id)
    ElMessage.success('刷新成功')
    await Promise.all([loadDevices(), loadStatistics()])
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  }
}

// 发现设备
const discoverDevices = () => {
  router.push('/discovery')
}

// 刷新设备列表
const refreshDevices = async () => {
  await Promise.all([loadDevices(), loadStatistics()])
}

// 加载设备列表
const loadDevices = async () => {
  try {
    loading.value = true
    await deviceStore.fetchDevices({
      page: currentPage.value,
      size: pageSize.value,
      search: searchKeyword.value,
      status: statusFilter.value,
      manufacturer: manufacturerFilter.value,
      enabled: enabledFilter.value,
      sortField: sortField.value,
      sortOrder: sortOrder.value
    })
  } catch (error) {
    ElMessage.error('加载设备列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const stats = await deviceStore.getStatistics()
    Object.assign(statistics.value, stats)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败: ' + error.message)
  }
}

// 处理设备表单提交
const handleDeviceSubmit = async deviceData => {
  try {
    if (isEditing.value) {
      await deviceStore.updateDevice(editingDevice.value.id, deviceData)
      ElMessage.success('设备更新成功')
    } else {
      await deviceStore.addDevice(deviceData)
      ElMessage.success('设备添加成功')
    }

    deviceFormVisible.value = false
    await Promise.all([loadDevices(), loadStatistics()])
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 重置表单
const resetForm = () => {
  editingDevice.value = null
  isEditing.value = false
}

// 生命周期
onMounted(async () => {
  await Promise.all([loadDevices(), loadStatistics()])
})

// 监听路由变化
watch(
  () => router.currentRoute.value.query,
  () => {
    // 从URL参数恢复筛选条件
    const query = router.currentRoute.value.query
    if (query.search) searchKeyword.value = query.search
    if (query.status) statusFilter.value = query.status
    if (query.manufacturer) manufacturerFilter.value = query.manufacturer
    if (query.enabled) enabledFilter.value = query.enabled
    if (query.page) currentPage.value = parseInt(query.page)
    if (query.size) pageSize.value = parseInt(query.size)
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.devices-page {
  padding: 0;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .header-left {
      h2 {
        margin: 0 0 8px 0;
        color: var(--el-text-color-primary);
      }

      p {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .filter-card {
    margin-bottom: 16px;

    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .filter-left {
        display: flex;
        gap: 12px;
        align-items: center;
      }

      .filter-right {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
  }

  .stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 16px;

    .stat-item {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: white;

          &.online {
            background: linear-gradient(135deg, #67c23a, #85ce61);
          }

          &.total {
            background: linear-gradient(135deg, #409eff, #66b1ff);
          }

          &.enabled {
            background: linear-gradient(135deg, #67c23a, #85ce61);
          }

          &.disabled {
            background: linear-gradient(135deg, #f56c6c, #f78989);
          }
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-regular);
            margin-top: 4px;
          }
        }
      }
    }
  }

  .device-list-card {
    .device-name-cell {
      display: flex;
      align-items: center;
      gap: 12px;

      .device-avatar {
        flex-shrink: 0;
      }

      .device-info {
        .name {
          font-weight: bold;
          color: var(--el-text-color-primary);
        }

        .model {
          font-size: 12px;
          color: var(--el-text-color-regular);
          margin-top: 2px;
        }
      }
    }

    .device-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 16px;

      .device-card {
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        padding: 16px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          border-color: var(--el-color-primary);
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        &.selected {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        }

        .card-body {
          text-align: center;
          margin-bottom: 16px;

          .device-avatar-large {
            position: relative;
            display: inline-block;
            margin-bottom: 12px;

            .device-status {
              position: absolute;
              bottom: 4px;
              right: 4px;
              width: 16px;
              height: 16px;
              border-radius: 50%;
              border: 2px solid white;

              &.online {
                background: var(--el-color-success);
              }

              &.offline {
                background: var(--el-color-danger);
              }

              &.connecting {
                background: var(--el-color-warning);
              }

              &.error {
                background: var(--el-color-danger);
              }
            }
          }

          .device-details {
            .device-name {
              font-size: 16px;
              font-weight: bold;
              color: var(--el-text-color-primary);
              margin: 0 0 4px 0;
            }

            .device-model,
            .device-ip,
            .device-manufacturer {
              font-size: 14px;
              color: var(--el-text-color-regular);
              margin: 2px 0;
            }
          }
        }

        .card-footer {
          .device-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;

            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 12px;
              color: var(--el-text-color-regular);
            }
          }

          .device-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }
      }

      .empty-state {
        grid-column: 1 / -1;
        padding: 60px 0;
      }
    }

    .pagination-wrapper {
      margin-top: 24px;
      text-align: center;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .devices-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-right {
        width: 100%;
        justify-content: flex-start;
        flex-wrap: wrap;
      }
    }

    .filter-card .filter-row {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .filter-left,
      .filter-right {
        flex-wrap: wrap;
        justify-content: flex-start;
      }
    }

    .stats-row {
      grid-template-columns: repeat(2, 1fr);
    }

    .device-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>
